import numpy as np

def show(k, x):
    print('第{}次迭代:'.format(k))
    for e in x:
        print(e)
    print()
    
def gs(A,b,t,e):  
    n = A.shape[0]
    x = np.arange(n).reshape((-1,1))
    x1 = np.zeros((n,1))
    cnt = 0  # 迭代次数
    pre = 1  # 精度
    while cnt < t and pre > e:
        for i in range(0,n):  # 得到迭代结果
            s1 = 0   
            for j in range(0,i):
                s1 += A[i][j]*x1[j][0]
            s2 = 0  
            for j in range(i+1,n):
                s2 += A[i][j]*x[j][0]
            s = b[i][0] - s1 - s2
            x1[i][0] = s/A[i][i] 
            
        cnt += 1
        show(cnt, x1)  # 输出迭代结果
        pre = 0
        for i in range(n):  # 计算精度
            pre = abs(x1[i][0]-x[i][0])
        pre /= n
        # print(pre)
        x = x1.copy()  # 更新迭代结果
    return x1
             


if __name__ == '__main__':
    # A = np.array([[10,-1,-2], [-1, 10, -2], [-1, -1, 5]])  # 注意python 矩阵不能用空格
    # b = np.array([72,83,42]).reshape((-1,1))
    # A = np.array([[12., -3, 3],[-18, 3, -1], [1, 1, 1]])  # attention here decimal point 
    # b = np.array([15., -15, 6]).reshape((-1,1))
    A = np.array([[1., 1, 1],[2, 3, 4], [1, 1, 5]])  # attention here decimal point 
    b = np.array([1, 3, 5]).reshape((-1,1))
    x = gs(A, b, 100, 1e-6)  # 迭代次数最多为100,精度为1e-6
    print('Ans:')
    for e in x:
        print(e)





